package com.example.demo.controller;


import com.example.demo.enums.ResultCodeEnum;
import com.example.demo.model.BlogInfo;
import com.example.demo.model.Result;
import com.example.demo.model.UserInfo;
import com.example.demo.service.BlogService;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.lang.Assert;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private static Logger log = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/login")
    public Result login(String userName,String password)
    {
        if(!StringUtils.hasLength(userName) && !StringUtils.hasLength(password))
        {
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "账号或密码不能为空");
        }

        UserInfo userInfo = userService.selectUserInfoByName(userName);
        if(userInfo == null) //如果不存在
        {
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "用户不存在");
        }
        if(!password.equals(userInfo.getPassword())) //如果密码不对
        {
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
        }

        //账号密码正确的情况下

        //用一个map保存一下用户的部分信息
        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id",userInfo.getId());
        cliams.put("name",userInfo.getUserName());

        String jwt = JwtUtils.genJWT(cliams); //生成token
        return Result.success(jwt); //返回token

    }


    //获取用户信息
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request)
    {
        String userToken = request.getHeader("user_token_header");

        //从token中获取用户id,因为在设置JWT时,用户的信息中含有用户的id
        Integer userId = JwtUtils.getUserIdFromToken(userToken);
        Assert.notNull(userId,"用户未登录");
        UserInfo userInfo =  userService.selectUserInfoById(userId);
        return userInfo;
    }


    //根据博客id获取作者id,根据作者id获取作者信息
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId)
    {
        Assert.notNull(blogId,"博客Id不能为null");
        return userService.selectAuthorByBlogId(blogId);
    }


}
